package org.scep.model;

import java.io.*;

/**
 * 处理文件存储
 * @author chenhongzhao 2008.3.20
 * @since 1.0.0
 */
public class FileAccess implements Serializable
{
	private static final long serialVersionUID = 7143298302360896851L;
	RandomAccessFile savedFile;
	long position;

	public FileAccess() throws IOException
	{
		this("", 0);
	}

	/**
	 * @param filePath 文件存储地址
	 * @param position 数据写入的指针
	 * @throws IOException
	 */
	public FileAccess(String filePath, long position) throws IOException
	{
		savedFile = new RandomAccessFile(filePath, "rw");
		this.position = position;
		savedFile.seek(position);
	}

	public synchronized int write(byte[] b, int nStart, int nLen) throws IOException
	{
		int n = -1;
		savedFile.write(b, nStart, nLen);
		n = nLen;
		return n;
	}
	
	public synchronized int read(byte[] b, int nStart, int nLen) throws IOException{
		return savedFile.read(b, nStart, nLen);
	}
	
	public synchronized void close() throws IOException{
		if(savedFile != null){
			savedFile.close();
		}
	}

}
